import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { ProductCard, Stepper, CheckboxGroup, Checkbox, Image, SubmitBar, SwipeCell, Button } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Ellipsis } from "@react-vant/icons";
import TopTitleBar from "../../components/TopTitleBar";
import { myContext } from '../../context';
import { baseURL } from '../../utils/contants';
import './index.css';
import { data } from "browserslist";
import axios from "../../utils/axios";
const ShoppingCartPage = () => {
    const navigate = useNavigate();
    const { shoppingCartConent, updateShoppingCartConent } = useContext(myContext);
    const ShoppingCartProducts = useRef(null);
    const SellectAll = useRef(null);
    const [cartItemIds, setCartItemIdArr] = useState([]);
    const [totalPrice, setTotalPrice] = useState(0);
    // const [ goodsCount, setGoodsCount ] = useState(null);
    const [isAllSelected, changeIsAllSelected] = useState(true)
    const settleCartAmount = () => {
        // 跳转到 createOrders 页面:
        navigate('/createOrders', {
            state: {
                // 是把选中的那几个 ！拿过去！
                cartItemIds: cartItemIds
            }
        })
    }
    const changeCheckBox = (name) => {
        // axios 把所有的 那个 cartItemIds 都 发请求 过去，
        // setTotalPrice()
        if (name.length !== 0) {
            axios.get(`/api/v1/shop-cart/settle?cartItemIds=${name}`).then(res => {
                if (res.data.message === 'SUCCESS') {
                    setCartItemIdArr(name)
                    // 数组 for 循环之后，累加：
                    const a = res.data.data.map(d => {
                        return d.goodsCount * d.sellingPrice
                    })
                    let tempTotalPrice = 0;
                    setTotalPrice(a.reduce((value1, value2) => value1 + value2, tempTotalPrice) * 100)
                }
            })
        } else {
            setTotalPrice(0)
        }
    }
    const isAllSelect = (e) => {
        if (e) {
            changeIsAllSelected(true)
            ShoppingCartProducts.current.toggleAll(true)
        } else {
            changeIsAllSelected(false)
            ShoppingCartProducts.current.toggleAll()
        }
    }
    const updateProductCount = (goodsCount, cartItemId) => {
        axios.put('/api/v1/shop-cart', data = {
            // put 的 data 要直接 =， 而且需要 引入！！！
            cartItemId,
            goodsCount
        }
        ).then(res => {
            if (res.data.message === 'SUCCESS') {
                getShoppingCartCount()
            }
        })
    }
    const handleStepperChange = useCallback((value, cartItemId) => {
        // 这里 应该 setVal：
        // 把步进器里面的value 给 发送出去，
        updateProductCount(value, cartItemId);
    }, [])
    const preventDefaultChange = (e) => {
        // 阻止事件冒泡！
        // 不然 点击了内容里面的东西，也会触发外层的 CheckBox 选择！
        //能不能防止事件冒泡？？', e);
        e.stopPropagation()
    }
    const getShoppingCartCount = () => {
        axios.get('/api/v1/shop-cart').then(res => {
            if (res.data.message === 'SUCCESS') {
                //如果是 SUCCESS， 就说明 aixos 成功，
                // 应该在 axios里面去设置一个相应拦截？？？？
                updateShoppingCartConent(res.data.data)
                const a = res.data.data.map(d => {
                    return d.goodsCount * d.sellingPrice
                })
                let tempTotalPrice = 0;
                setTotalPrice(a.reduce((value1, value2) => value1 + value2, tempTotalPrice) * 100)

            }
        })
    }

    const handleDeleteCartProduct = (cartItemId) => {
        // axios 请求：
        axios.delete(`/api/v1/shop-cart/${cartItemId}`).then(res => {
            // 就要重新获取一次页面！
            if (res.data.message === 'SUCCESS') {
                getShoppingCartCount();
            }
        })

    }
    useEffect(() => {
        // 为什么 它原地 刷新的时候，没有CheckboxGroup 选中的 值？？
        getShoppingCartCount();
        shoppingCartConent.length > 0 && ShoppingCartProducts.current.toggleAll(true);
    }, [])

    return (
        <div className="shoppingCartPage" >
            <TopTitleBar
                topTitleBarBackgroundColor="#fff"
                leftIcon={
                    <div style={{ opacity: 0 }} >
                        <Ellipsis />
                    </div>
                }
                intermediateContentText="购物车"
                rightIcon={
                    <Ellipsis />
                }
            />
            {

                shoppingCartConent.length > 0 ? (
                    <div className="mainContent">
                        <CheckboxGroup checked={true} checkedColor='#1baeae' ref={ShoppingCartProducts} onChange={(name) => changeCheckBox(name)} >
                            {
                                shoppingCartConent.map(product => {
                                    return <Checkbox key={product.goodsId} checked={true} name={product.cartItemId} >
                                        <SwipeCell stopPropagation={true} rightAction={<Button className="deleteBtn" type='danger' onClick={(cartItemId = product.cartItemId) => handleDeleteCartProduct(cartItemId = product.cartItemId)}  >删除 </Button>} >
                                            <div className="ShoppingCartProducts" onClick={(e) => preventDefaultChange(e)}>
                                                <div className="goodsImg">
                                                    <Image lazyload src={String(product.goodsCoverImg).startsWith('http') ? product.goodsCoverImg : baseURL + product.goodsCoverImg} />
                                                </div>
                                                <div className="goodsContents">
                                                    <div className="goodsRightTop">
                                                        <div className="goodsTitle">
                                                            {product.goodsName}
                                                        </div>
                                                        <div className="goodsCount">
                                                            x {product.goodsCount}
                                                        </div>
                                                    </div>
                                                    <div className="goodsRightFooter">
                                                        <div className="goodsRightFooterPrice">
                                                            {'¥' + product.sellingPrice}
                                                        </div>
                                                        <div className="stepper">
                                                            {/* 使用 默认值传参！ */}
                                                            < Stepper onChange={(value, cartItemId = product.cartItemId) => handleStepperChange(value, cartItemId = product.cartItemId)} min={1} max={5} defaultValue={product.goodsCount} />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </SwipeCell>
                                    </Checkbox>
                                })
                            }
                        </CheckboxGroup>

                        <div className="submitBar">
                            <SubmitBar
                                buttonColor='#1baeae'
                                price={totalPrice}    // 这是依据所选择的数组 里面的 （count * price） 累加 ，计算出来的总数
                                buttonText="结算"
                                onSubmit={settleCartAmount}
                                decimalLength={2}
                            >
                                <Checkbox ref={SellectAll} name='sellectAll' checked={isAllSelected} checkedColor='#1baeae' onChange={(e) => isAllSelect(e)}>全选</Checkbox>
                            </SubmitBar>
                        </div>
                    </div>
                ) : (
                    <div className='noShoppingCart'>
                        <Image
                            src='https://s.yezgea02.com/1604028375097/empty-car.png'
                        />
                        <div className="noShoppingCartText">
                            购物车空空如也
                        </div>
                        <Button
                            onClick={() => navigate('/')}
                            text='前往选购'
                            block
                            round
                            color='#1baeae'
                        />
                    </div>
                )
            }

        </div >
    )
}

export default ShoppingCartPage;